import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 判断岛屿数量
     * @param grid char字符型二维数组
     * @return int整型
     */
    private boolean[][] visited;
    private int m;
    private int n;
    public int solve (char[][] grid) {
        // write code here
        m = grid.length;
        n = grid[0].length;
        visited = new boolean[m][n];
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1' && !visited[i][j]) {
                    findNext(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    private void findNext(char[][] grid, int row, int col) {
        if (row - 1 >= 0 && grid[row - 1][col] == '1' && !visited[row - 1][col]) {
            visited[row - 1][col] = true;
            findNext(grid, row - 1, col);
        }
        if (row + 1 < m && grid[row + 1][col] == '1' && !visited[row + 1][col]) {
            visited[row + 1][col] = true;
            findNext(grid, row + 1, col);
        }
        if (col - 1 >= 0 && grid[row][col - 1] == '1' && !visited[row][col - 1]) {
            visited[row][col - 1] = true;
            findNext(grid, row, col - 1);
        }
        if (col + 1 < n && grid[row][col + 1] == '1' && !visited[row][col + 1]) {
            visited[row][col + 1] = true;
            findNext(grid, row, col + 1);
        }
    }
}